;; "latup" stands for "LAmbda, the ultimate preprocessor".
;;
;; This is a preprocessor for files that contain scheme expressions, embedded within
;; another language. The scheme expressions are evaluated and their values are 
;; emitted to the output stream, the way a c preprocessor is used.
;;
;; Scheme quotations come in one of 3 forms:
;; #{x} - evaluates the variable x and splices its value
;; #(expr ...) - evaluates the parenthesized expression and splices the result
;; #[expr ...] - evaluates the bracketed expression without splicing the result
;;
;; All values are spliced using the display procedure.

(module latup
	(export preprocess-current-io eval-env))

(define eval-env (interaction-environment))

(define (next-is? c) (eq? (peek-char) c))

(define (re) (eval (read) eval-env))

(define (rep) (display (re)))

(define (expect-char c)
  (define char-read (read-char))
  (if (not (eq? char-read c))
      (error "expect-char" (format "Expected '~A', but encountered '~A'" c char-read) c)))

(define (handle-preprocessor-exp)
  (cond ((next-is? #\( ) (rep))
	((next-is? #\[ ) (re))
	((next-is? #\{ ) (read-char) (rep) (expect-char #\} ))
	(else (write-char #\#))))

(define (preprocess-current-io)
  (let loop ()
    (let ((c (read-char)))
      (cond ((eof-object? c) #f)
	    ((eq? c #\#) (handle-preprocessor-exp) (loop))
	    (else 
	     (write-char c)
	     (loop))))))

